﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.SessionState;
using SalesSys.BLL;
using SalesSys.Comm.Utility;
using FluentScheduler;
using SalesSys.WebCore;

namespace SalesSys.Site
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            SalesSys.DAL.WXDbContext.Init();
            RepositoryFactory.FactoryCreateMode = GetNowContext;

            JobManager.Initialize(new WebJobReg());
        }
       protected void Session_Start(object sender, EventArgs e)
        {
            Session.Timeout = 30;
        } 
        private static RepositoryFactory GetNowContext()
        {
            var contextName = RepositoryFactory.RepositoryFactoryAtHttpContextName;
            if (HttpContext.Current == null)
            {
                var cll = CallContext.GetData(contextName) as RepositoryFactory;
                if (cll == null)
                {
                    cll = new RepositoryFactory();
                    CallContext.SetData(contextName, cll);
                }
           
                return cll;
            }
            //设置创建办法
            var rf = HttpContext.Current.Items[RepositoryFactory.RepositoryFactoryAtHttpContextName] as RepositoryFactory;
            if (rf == null)
            {
                rf = new RepositoryFactory();
                HttpContext.Current.Items[RepositoryFactory.RepositoryFactoryAtHttpContextName] = rf;
            }
            //设置上下文中用户信息
            //rf.UnitContext.ContextItem[RepositoryFactory.ContextUserInfoSign] = ClientHelper.ClientInfo;
            //rf.UnitContext.ContextItem[RepositoryFactory.ContextAdminInfoSign] = AdminHelper.AdminInfo;
 
            return rf;
        }

        public override void Init()
        {
            this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
            base.Init();
        }
    }
}
